<?php
namespace addons\venue\job;
use app\admin\model\venue\activity\UserActivity;
use app\admin\model\venue\area\Rule;
use app\admin\model\venue\Coupon;
use app\admin\model\venue\coupon\Receive;
use app\admin\model\venue\goods\Goods;
use app\admin\model\venue\lesson\UserLesson;
use app\admin\model\venue\order\Order;
use app\admin\model\venue\venue\Relationship;
use app\admin\model\venue\venue\Reserve;
use think\Cache;
use think\Db;
use think\Log;
use think\queue\Job;

/**
 * 用于处理超时订单自动取消
 */
class Overtime
{
    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        Log::log("进入队列");
        //执行业务处理
        if($this->doJob($data)){
            $job->delete();//任务执行成功后删除
            Log::log("dismiss job has been down and deleted");
        }else{
            //检查任务重试次数
            if($job->attempts() > 3){
                Log::log("dismiss job has been retried more that 3 times");
                $job->delete();
				Db::close();
            }else{
                $job->release(2);
            }
        }
    }


    /**
     * 根据消息中的数据进行实际的业务处理
     */
    private function doJob($data)
    {
        // 实际业务流程处理
        //查询该订单是否已付款
        $orderInfo = Order::get(['order_no'=>$data['orderNo']]);
            // Log::log("该订单已支付===>".$orderInfo);
            // Log::log("该订单已支付===>2222".$data);
        if (!$orderInfo){
            return true;
        }
        if ($orderInfo->status != 1){
            //订单已付款
            Log::log("该订单已支付".$data['orderNo']);
            return true;
        }else{
            Log::log("该订单未支付".$data['orderNo']);
            Db::startTrans();
            try {
                //订单已超时 更新订单状态
                $res = Order::update(['status'=>5],['id'=>$orderInfo['id']]);
                Log::log("订单更新状态".Order::getLastSql());
                Log::log("订单更新状态".$res);
                if ($orderInfo->order_type == 1){
                    //增加库存
                    $goods = Goods::where("id",$orderInfo->goods_id)->field("id,stock")->find();
                    $res2  = Goods::update(["stock"=>bcsub($goods['stock'],$orderInfo->goods_count)],["id"=>$goods['id']]);
                    Log::log("库存更新状态".$res2);
                }elseif ($orderInfo->order_type == 2){
                    //取消场次预定
                    foreach ($data['venueDetail'] as $val){
                        //获取规则
                        $rules = Relationship::where(['id'=>$val['areaId']])->value("rule_id");
                        $interval = Rule::get($rules);
                        foreach ($val['times'] as $v) {
                            //根据间隔时间获取开始和结束时间
                            $startTimes = $v['time'];
                            $str_time = strtotime($data['fixed_date'] . " " . $v['time']);
                            $end_time = bcadd($str_time, bcmul($interval['interval_time'], 3600));
                            $endTimes = date("H:i", $end_time);
                            // $res3= Reserve::update([
                            //     'user_id'       =>  $orderInfo->user_id,
                            //     "area_id"       =>  $val['areaId'],
                            //     "fixed_date"    =>  $data['fixed_date'],
                            //     "start_times"   =>  $startTimes,
                            //     "end_times"     =>  $endTimes
                            // ]);
                            
                            
                             Reserve::where("order_id",$orderInfo['id'])->update(['order_status'=>1]);
                            //清除redis缓存
                            $key = $data['venue_id'].'-'.$val['areaId'].'-'.$data['fixed_date'].'-'.$startTimes.'-'.$endTimes;
                            Cache::rm($key);
                        }
                    }


                    // Log::log("场次更新状态".$res3);
                }elseif ($orderInfo->order_type == 3){
                    //取消报名课程
                    $res4 = UserLesson::where("order_id",$orderInfo['id'])->update(['order_status'=>1]);
                    Log::log("课程更新状态".$res4);
                }elseif ($orderInfo->order_type == 4){
                    //取消活动报名
                    $res5 = UserActivity::destroy([
                        "user_id"       =>  $orderInfo->user_id,
                        "activity_id"   =>  $orderInfo->activity_id,
                    ]);
                    Log::log("活动更新状态".$res5);
                }
                //判断是否使用优惠券
                if ($orderInfo->coupon_id > 0){
                    //更新优惠券为未使用，判断优惠券是否过期
                    $coupon = Coupon::get($orderInfo->coupon_id);
                    if (time() > $coupon->end_time){
                        $res5 = Receive::update(['state'=>-1],["user_id"=>$orderInfo['user_id'],"coupon_id"=>$orderInfo->coupon_id]);
                    }else{
                        $res5 = Receive::update(['state'=>0],["user_id"=>$orderInfo['user_id'],"coupon_id"=>$orderInfo->coupon_id]);
                    }
                    Log::log("优惠券更新状态".$res5);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                Log::log($e->getMessage());
                return false;
            }
            return true;
        }
    }
}